package com.enzoism.springboot.fastjson.request;

import com.enzoism.springboot.fastjson.group.First;
import com.enzoism.springboot.fastjson.group.Group;
import com.enzoism.springboot.fastjson.group.Second;
import com.enzoism.springboot.fastjson.result.RequestResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
public class IndexController {

    @GetMapping("/")
    public UserModel getUserModel(){
        UserModel userModel = new UserModel();
        userModel.setId(100);
        userModel.setCreateTime(new Date());
        userModel.setName("Enzoism");
        userModel.setRemarks("Remarks");
        userModel.setNickName("enzo");
        return userModel;
    }

    @PostMapping("/")
    public UserModel getUserModel(@RequestBody UserModel userModel){
        log.info("------>传递的参数："+userModel);
        return userModel;
    }

    @PostMapping("/validation")
    public UserModel validationUserModel(@Validated @RequestBody UserModel userModel){
        log.info("------>传递的参数："+userModel);
        return userModel;
    }

    @PostMapping("/validation2")
    public RequestResult validationUserModel(@Validated @RequestBody UserModel userModel, BindingResult result){
        log.info("------>传递的参数："+userModel);
        List<FieldError> fieldErrors = result.getFieldErrors();
        List<String> collect = fieldErrors.stream()
                .map(o -> o.getDefaultMessage())
                .collect(Collectors.toList());
        return RequestResult.success(collect);
    }

    @PostMapping("/first")
    public PeopleModel validationPeopleModel1(@Validated({First.class}) @RequestBody PeopleModel model){
        log.info("------>传递的参数："+model);
        return model;
    }

    @PostMapping("/second")
    public PeopleModel validationPeopleModel2(@Validated({Second.class}) @RequestBody PeopleModel model){
        log.info("------>传递的参数："+model);
        return model;
    }

    @PostMapping("/group")
    public PeopleModel validationPeopleModel3(@Validated({Group.class}) @RequestBody PeopleModel model){
        log.info("------>传递的参数："+model);
        return model;
    }

    @PostMapping("/equals")
    public PeopleModel validationPeopleModel4(@Valid @RequestBody PeopleModel model){
        log.info("------>传递的参数："+model);
        return model;
    }
}
